<template>
  <div style="margin: 10px">
    <div>
      <el-form :inline="true" label-width="auto" style="max-width: 600px">
        <el-form-item label="品牌名称">
          <el-input v-model="queryParams.name" placeholder="请输入品牌名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="initData" >搜索</el-button>
          <el-button type="primary" :icon="Refresh" @click="initReset">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="mb-4" style="margin-top: 10px">
        <el-button type="primary" :icon="Plus"  v-hasPermi="['product:brand:add']" @click="title='添加品牌';dialogFormVisible=true">新增</el-button>
        <el-button type="success" :icon="Edit"  >修改</el-button>
        <el-button type="danger" :icon="Delete" v-hasPermi="['product:brand:remove']" @click="removeAllButton">删除</el-button>

        <el-dialog v-model="dialogFormVisible" :title="title" width="500">
          <el-form >
            <el-form-item label="品牌名称" :label-width="formLabelWidth">
              <el-input v-model="brand.name" placeholder="请输入品牌的名称" autocomplete="off" />
            </el-form-item>
            <el-form-item label="品牌图标" :label-width="formLabelWidth">
              <el-upload
                  class="avatar-uploader"
                  :action= "uploadUrl"
                  :name="file"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleUploadLogoSuccess"
              >
                <img v-if="brand.logo" :src="brand.logo" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>

          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveOrUpdate">
                提交
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <!--品牌数据表格 -->
    <div style="margin-top: 10px">
      <el-table :data="brands" stripe style="width: 100%" @selection-change="handselectionchange">
        <el-table-column type="selection" width="50"/>
        <el-table-column prop="name" label="品牌名称" />
        <el-table-column prop="logo" label="品牌图标" >
          <template #default="scope">
            <img :src="scope.row.logo" style="width: 40px;height: 40px">
          </template>

        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column  label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" v-hasPermi="['product:brand:edit']" @click="handleUpdate(scope.row.id)">修改</el-button>
            <el-button link type="primary" size="small" v-hasPermi="['product:brand:remove']" @click="removeOne(scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <!--数据分页导航条  pagination表示绑定查询上一页或者下一页分页数据的函数 -->
       <div>
         <pagination
             v-show="total > 0"
             :total="total"
             v-model:page="queryParams.pageNum"
             v-model:limit="queryParams.pageSize"
            @pagination="initData"
         />

       </div>
    </div>
    </div>
  </div>

</template>

<script setup>
const title = ref("添加品牌")

const handleSaveOrUpdate = async()=>{
      if (brand.value.id){
        //更新
        handleUpdateValue()
      }else {
        handleSave()
      }
}

const handleUpdateValue = async()=>{
      await updateBrand(brand.value)
      ElMessage("修改成功")
}

const handleUpdate = async(id)=>{
     const{data} = await getBrand(id)
      brand.value = data
      title.value = "修改品牌"
  dialogFormVisible.value=true
}

const handleSave=async ()=>{
  await addBrand(brand.value)
  ElMessage("新增成功")
  initData()
}
//引入获取token的工具类
import { getToken } from '@/utils/auth'

const uploadUrl = import.meta.env.VITE_APP_BASE_API+"/file/upload"

const headers = {'Authorization':'Bearer ' +getToken()}
const handleUploadLogoSuccess = (r)=>{
  if (+r.code ===200){ // +code表示把code转为数字
   brand.value.logo = r.data.url
  }
  else {
    ElMessage.error(r.msg )
  }


}


//新增更新品牌对话框: false默认隐藏
const dialogFormVisible  = ref(false)

//表格label宽度属性
const formLabelWidth  = '120'

//收集要新增/更新 的品牌数据的属性
const brand = ref({
  name:'',
  logo:null
})

onMounted(()=>{
  initData();

})
import {ElMessage, ElMessageBox} from "element-plus";
import { h } from 'vue'

import {

  Search,
  Refresh,
    Plus,
    Delete,
    Edit
} from '@element-plus/icons-vue'

import {
listBrand,
delBrand,
    addBrand,
    updateBrand,
    getBrand,
  listAllBrand
} from '@/api/product/brand.js'
//分页导航条属性
/*const pageNum =ref(1)
const pageSize =ref(3)*/
const total = ref(100)
const queryParams = ref({
  pageNum : 1,
  pageSize :3,
  name : null
})
const brands = ref([])
const initData= async()=>{
  //从返回的响应对象中获取rows和total两个属性，使用t接收total属性值
    const {rows,total:t} = await listBrand(queryParams.value)
    brands.value = rows
      total.value = t
}

const initReset=()=>{
  queryParams.value = {
    pageNum : 1,
    pageSize :3,
    name : null
  }
}
const removeOne= (row)=>{
  ElMessageBox.confirm(
      `是否确认删除[${row.name}]`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async() => {
        //点击确认删除按钮的回调
        await delBrand(row.id)

        ElMessage({
          type: 'success',
          message: '删除成功',

        })
        initData()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}
const selectBrands = ref([])
const handselectionchange=(newSelection)=>{
    selectBrands.value = newSelection

}
//删除按钮事件函数
const removeAllButton=()=>{
  const selectIds = selectBrands.value.map((brand) => (brand.id))
  if (!selectBrands.value || selectBrands.value.length ===0){
    ElMessage("请选择你要删除的品牌")
    return
  }

  ElMessageBox.confirm(
      "是否确认删除所有选中内容",
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async() => {
    //点击确认删除按钮的回调
    await delBrand(selectIds)

    ElMessage({
      type: 'success',
      message: '删除成功',

    })
    initData()
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })


}


</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>